<?php

namespace zhtfrontend\modules\phone\controllers;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\models\datas\Admissionfee;
use common\models\datas\Classhourfee;
use common\models\datas\Customer;
use common\models\datas\Student;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\StudentCheck;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\Response;
use yii\helpers\Html;
use common\models\datas\CardAttr;

class DefaultController extends Controller
{
    public $clock = true;
    public function actionIndex()
    {
        if(\Yii::$app->user->isGuest){
            return $this->redirect(Fun::url(['site/login']));
        }
        $mids = Fun::getMechanicIds();
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'telephone') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $telephone_id = \Yii::$app->request->post('telephone_id');
            $customer = Customer::find()->where(['mobile' => $telephone_id])->andWhere(['site_id'=>Fun::getSiteId()])->one();//1122
            $ajax_object = new AjaxObject();
            if ($customer !== null && $customer->card_id !== null) {
                $user_id = $customer->id;//获取持有当前卡号的用户的id
                //获取当前用户的孩子的信息(可能会有两个孩子)
                $student = Student::findone(['customer_id'=>$user_id]);//997
                //在class_student表查找改学生的已开班的课程  数组
                $class_student =ClassStudent::find()->select('class_manage_id')->where(['student_id' => $student->id, 'status' => 1])->column();

                //机构登陆只查询自己的课程
                if(!empty($mids)){
                    $class_student = ClassManage::find()->select('class_id')->where(['class_id'=>$class_student,'mechanic_id'=>$mids])->column();
                }
                $id = [];
                $str = '';
                if ($class_student != null) {

                    $check_status = 1;//默认已打卡
                    //foreach ($class_student as $k => $v) {
                        //查询class_manage表 查询今天 对应时间的课程
                        //今天开始  结束时间戳
                        $time_start = strtotime(date('Y-m-d'));
                        $time_end = $time_start + 86399;

                        //根据开始 结束时间条件 查找
                        $time_1 = date('Hi',time()+2*60*60);
                        $time_2 = date('Hi',time()-2*60*60);


                        //查找今天的课程  可能一天上两节课  数组
                        $class_lessons = ClassLesson::find()->where(['class_id'=>$class_student])
                            ->andwhere(['>=','class_date',$time_start])
                            ->andwhere(['<=','class_date',$time_end])
                            ->andwhere(['<=','start_time',$time_1])
                            ->andwhere(['>=','end_time',$time_2])
                            ->all();
                        if(!empty($class_lessons)) {
                            $str .= '<img src="images/sh.gif" width="25%"/>
                                        <h2>欢迎<span>' . Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                                        <p >你在1小时内的课程如下：</p>';
                            $str .='<table border="0" cellspacing="0" cellpadding="0" class="cj-class-content">
                                        <thead>
                                            <tr>
                                                <th>上课老师</th>
                                                <th>时间</th>
                                                <th>状态</th>
                                                <th>课程名称</th>
                                                <th class="last">上课地点</th>
                                            </tr>
                                        </thead>';
                            foreach ($class_lessons as $val) {
                                $check_start = $val->class_date - (2 * 60 * 60);//课程开始前的2个小时
                                $check_end = $time_start + (substr($val->end_time, -2) * 60) + (floor($val->end_time/100) * 60 * 60);//课程结束后的一个半小时
                                //找到符合条件的class_lesson
                                $time = time();
                                $class_state = '未打卡';
                                if ($check_start <= $time && $time <= $check_end) {
                                    $student_check = StudentCheck::findone(['class_lesson_id'=>$val->lesson_id]);
                                    $lesson_student = LessonStudent::findOne(['lesson_id'=>$val->lesson_id]);
                                    if(isset($student_check) && isset($lesson_student)){

                                        if ($student_check->status != 0 && $lesson_student->status != 0) {
                                            $class_state = '已打卡';

                                        } else {
                                            $class_state = '未打卡';
                                            $id[] = $val->lesson_id;
                                            $check_status = 0;

                                        }

                                    }

                                    //展示信息
                                    //查询class_manage表数据
                                    $nomal_start=isset($val->start_time)? Util::getTime($val->start_time):'';
                                    $nomal_end=isset($val->end_time)? Util::getTime($val->end_time):'';
                                    $class_manage = ClassManage::findOne(['class_id' => $val->class_id]);
                                    if ($class_manage->is_old == 0) {
                                        //若是新班 获取课程的相关的信息
                                        $course_infomation = GoodsAttr::find()->where(['goods_id' => $class_manage->associate_id])->indexBy('obj_type')->asArray()->all();

                                        $str .= '
                                        <tbody>
                                            <tr>
                                                <td>' . Html::encode(isset($course_infomation['teacher']['value']) ? $course_infomation['teacher']['value'] : '') . '</td>
                                                <td>' . Html::encode($nomal_start) . '-' . Html::encode($nomal_end) . '</td>
                                                <td>' . Html::encode($class_state) . '</td>
                                                <td width="215px">' . Html::encode(isset($val->title) ? $val->title : '') . '</td>
                                                <td>' . Html::encode($course_infomation['classroom_name']['value'] ? $course_infomation['classroom_name']['value'] : '') . '</td>
                                            </tr>
                                        </tbody>';
                                    } else {
                                        //若为老生 查找arrangement表
                                        $course_infomation = Arrangement::findone(['id' => $val->classManage->associate_id]);

                                        $str .= '
                                        <tbody>
                                            <tr>
                                                <td>' . Html::encode(isset($course_infomation->teacher->name) ? $course_infomation->teacher->name : '') . '</td>
                                                <td>' . Html::encode($nomal_start) . '-' . Html::encode($nomal_end) . '</td>
                                                <td>' . Html::encode($class_state) . '</td>
                                                <td width="215px">' . Html::encode(isset($val->title) ? $val->title : '') . '</td>
                                                <td>' . Html::encode(isset($course_infomation->classroom->name) ? $course_infomation->classroom->name : '') . '</td>
                                            </tr>
                                        </tbody>';
                                    }
                                }
                            }
                            $str .='</table>';
                            if($check_status == 0){
                                $ajax_object->data = array_values($id);
                                $str .= ' <button class="cj-lock-confirm" data-url1="' . Fun::url(["click/default/index"]) . '"  data-id="' . serialize($id) . '"></button>';
                            }else{
                                $ajax_object->data = 0;
                                $str .= ' <button class="cj-lock-confirm cj-lock-disable" data-url1="' . Fun::url(["click/default/index"]) . '"  data-id="' . serialize($id) . '"></button>';
                            }
                            $ajax_object->content = $str;
                        }else{
                            $str = '<img src="images/clock-sun.png" class="cj-clock-sun">
                            <img src="images/sh.gif" width="25%"/>
                            <h2>欢迎<span>'. Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                             <p>你在1小时内的课程如下：</p>
                             <p class="cj-clock-red">现在暂时没有您需要上的课程，在广场随便溜达溜达吧！</p>
                             <button class="cj-lock-confirm cj-lock-disable"></button>
                             ';
                            $ajax_object->data = '您没课';
                            $ajax_object->content = $str;
                        }
                    //}

                }else{
                    $str = '<img src="images/clock-sun.png" class="cj-clock-sun">
                            <img src="images/sh.gif" width="25%"/>
                            <h2>欢迎<span>'. Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                             <p>你在1小时内的课程如下：</p>
                             <p class="cj-clock-red">现在暂时没有您需要上的课程，在广场随便溜达溜达吧！</p>
                             <button class="cj-lock-confirm cj-lock-disable"></button>
                             ';
                    $ajax_object->data = '您没课';
                    $ajax_object->content = $str;
                }
            }else {
                $str='
                      <img src="images/clock-sun.png" class="cj-clock-sun">
                      <img src="images/clcok-question.gif" width="35%">
                      <p>很抱歉，你的卡号不存在</p>
                      <p class="p-small">请确认后重新打卡</p>
                      <button class="cj-lock-disableno" ></button>
                       ';
                $ajax_object->data = '卡号不存在';
                $ajax_object->content = $str;
            }
            return $ajax_object;
        }
        //下面是按钮点击部分的代码
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'status') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $lesson_id = \Yii::$app->request->post('id');
            $lesson_id = unserialize($lesson_id);
            if ($lesson_id == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
            }
            foreach($lesson_id as $id) {
                //根据传来的lesson_id 查找student_check lesson_student表
                $class_lesson = ClassLesson::findone(['lesson_id' => $id]);
                $student_check = StudentCheck::findone(['class_lesson_id' => $id]);
                $lesson_student = LessonStudent::findOne(['lesson_id' => $id]);
                if($class_lesson->status == 0){
                    $class_lesson->status =1;
                    $class_lesson->save(false);
                }
                if ($student_check->status != 0 && $lesson_student->status != 0) {
                    return 2;
                } else {
                    //如果class_lesson表状态==0 则修改状态
//                if($class_lesson->status == 0){
//                    $class_lesson->status = 1;
//                    $class_lesson->save(false);
//                }
                    //修改student_check表
                    $student_check->status = 1;
                    $student_check->created_at = time();
                    $student_check->save(false);
                    //修改lesson_student表
                    $lesson_student->status = 1;
                    $lesson_student->save(false);

                    //如果是打卡超过本课程的3分之一的话，就往表里面插入一条数据
                    $class_manage = ClassManage::findone(['class_id' => $class_lesson->class_id]);
                    if ($class_manage->is_old == 0) {
                        //查询总上课数
                        $class_count = ClassLesson::find()->where(['class_id' => $class_lesson->class_id])->count();
                        $count = $class_lesson->lesson;
                        $Proportion_number = $class_count / 3;
                        $Mechanic = Mechanic::findOne($class_manage->mechanic_id);
                        if($Mechanic->enrollment_ratio > 0){
                            $Proportion_number = ceil($class_count*($Mechanic->enrollment_ratio/100));
                        }
                        if ($Proportion_number < $count) {
                            $adminssionfee = Admissionfee::find()->where(['student_id' => $student_check->student_id, 'goods_id' => $class_manage->associate_id,'class_student_id'=>$student_check->id])->one();
                            $student=Student::findOne($student_check->student_id);
                            $customer = Customer::findOne($student->customer_id);
                            if ($adminssionfee == null) {
                                    $admission = new Admissionfee();
                                    $admission->customer_id = $customer->id;
                                    $admission->student_id = $student_check->student_id;
                                    $admission->mechanic_id = $class_manage->mechanic_id;
                                    $admission->class_id = $class_manage->class_id;
                                    $admission->class_student_id = $student_check->class_student_id;
                                    $admission->goods_id = $class_manage->associate_id;
                                    $admission->site_id = Fun::getSiteId();
                                    $admission->status = '0';
                                    $admission->created_at = time();

                                    $goods = Goods::findone(['id' => $class_manage->associate_id]);
                                    $classroom = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $class_manage->associate_id, 'obj_type' => 'classroom'])->one();
                                    $teacher = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $class_manage->associate_id, 'obj_type' => 'teacher'])->one();
                                    $student = Student::findone(['id' => $student_check->student_id]);
                                    $salesman = CardAttr::find()->where(['customer_id'=>$customer->id])->one();

                                    $student_age = date('Y') - $student->age;

                                    $admission->mechanic_name = $Mechanic->name;
                                    $admission->goods_name = $goods->name;
                                    $admission->admissionfee = $goods->admission_fee;
                                    $admission->classroom_id = $classroom->attribute_id;
                                    $admission->classroom_name = $classroom->value;
                                    $admission->teacher_id = $teacher->attribute_id;
                                    $admission->teacher_name = $teacher->value;
                                    $admission->class_date = $class_lesson->class_date;
                                    $admission->class_day = date('w', $class_lesson->class_date);
                                    $admission->class_start = $class_lesson->start_time;
                                    $admission->class_end = $class_lesson->end_time;
                                    $admission->customer_name = $customer->name;
                                    $admission->student_name = $student->name;

                                    $admission->cate_id = !empty($goods)?$goods->cat_id:0;
                                    $admission->mechanic_area = !empty($mechanic)?$mechanic->region:'';
                                    $admission->salesman_id = !empty($salesman)?$salesman->salesman_id:0;
                                    $admission->student_age = !empty($student_age)?$student_age:0;

                                    $admission->save(false);
                                }
                        }
                    }
                }
            }
            return 1;
        }
        return $this->render('index');
    }

    public function datetime($date){
        if($date=='星期一'){
            $date=1;
        }elseif($date=='星期二'){
            $date=2;
        }elseif($date=='星期三'){
            $date=3;
        }elseif($date=='星期四'){
            $date=4;
        }elseif($date=='星期五'){
            $date=5;
        }elseif($date=='星期六'){
            $date=6;
        }else{
            $date=7;
        }
    return $date;
    }
}
